<?php
// +----------------------------------------------------------------------
// | @filename AdminUserRepository.php
// +----------------------------------------------------------------------
// | @author 落花轻舞问君愁 <mwcx1990@qq.com>
// +----------------------------------------------------------------------
// | @datetime 2021-10-26 15:45:14
// +----------------------------------------------------------------------
// | @Description
// +----------------------------------------------------------------------
namespace Addons\Backend\Repositories;

use Addons\Backend\Models\AdminUser;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;

class AdminUserRepository extends BaseRepository
{
    protected $model;

    public function __construct(AdminUser $adminUser)
    {
        $this->model = $adminUser;
    }

    /**
     * 管理员列表筛选查询
     * @param $filters
     * @return mixed
     */
    public function queryList($filters)
    {
        return $this->model::query()->when($filters['id'], function ($query, $id) {
            $query->where('id', $id);
        })->when($filters['username'], function ($query, $username) {
            $query->where('username', 'LIKE', "%$username%");
        })->when($filters['nickname'], function ($query, $nickname) {
            $query->where('nickname', 'LIKE', "%$nickname%");
        })->when($filters['status'], function ($query, $status) {
            $query->where('status', $status);
        })->latest()->paginate($filters['per_page']);
    }

    /**
     * 根据用户名或手机号查找管理员
     * @param $value
     * @return mixed
     */
    public function findByUsernameOrMobile($value)
    {
        return $this->model::query()->where('username', $value)->orWhere('mobile', $value)->first();
    }

    /**
     * 更新
     * @param $data
     * @return Builder|Builder[]|Collection|Model|null
     */
    public function update($data)
    {
        $adminUser = $this->model::query()->findOrFail($data['id']);
        if (empty($data['password'])) unset($data['password']);
        $adminUser->fill($data);
        $adminUser->save();
        return $adminUser;
    }

    /**
     * 已分配的角色
     * @param $userId
     * @return mixed
     */
    public function assignedRoles($userId)
    {
        $adminUser = $this->model::query()->findOrFail($userId);
        return $adminUser->roles;
    }


    /**
     * 给管理员分配角色
     * @param $id
     * @param $roles
     * @return mixed
     */
    public function assignRoles($id, $roles)
    {
        return $this->model::query()->findOrFail($id)->syncRoles($roles);
    }

    /**
     * 根据userID获取管理员角色能访问的菜单路由
     * @param $userId
     * @return mixed
     */
    public function getUserMenus($userId)
    {
        $adminUser = $this->model::query()->findOrFail($userId);
        return $adminUser->with('roles.menus')->first();
    }
}
